/** 判断是否是非法页面 */
function IsIllegalPages(url = '') {
    const illegal = [
        'chrome://',
        'edge://',
        'about:',
        'moz-extension://',
        'res://',
        'view-source:',
        'devtools://',
        'https://ntp.msn.cn',
        'https://devtools.azureedge.net',
        'chrome-extension://',
    ];
    const flag = illegal.every((str) => !url.startsWith(str));
    return !flag;
}

/** v3 控制图标 */
function setIcon(tabId, url) {
    if (IsIllegalPages(url)) {
        chrome.action.setIcon({
            path: {
                16: 'icons/icon-grey.png',
                48: 'icons/icon-grey.png',
                64: 'icons/icon-grey.png',
                128: 'icons/icon-grey.png',
            },
            tabId,
        });
    } else {
        chrome.action.setIcon({
            path: {
                16: 'icons/icon.png',
                48: 'icons/icon.png',
                64: 'icons/icon.png',
                128: 'icons/icon.png',
            },
            tabId,
        });
    }
}

/** 插件初始化时触发 */
const handleExtensionInstalled = () => {
    chrome.runtime.onInstalled.addListener(({ reason }) => {
        switch (reason) {
            case 'install':
                console.log('[Plugin] 插件更新原因：首次安装');
                break;
            case 'update':
                console.log('[Plugin] 插件更新原因：重新加载');
                break;
            default:
                console.log('[Plugin] 插件更新原因：未知');
        }

        try {
            chrome.tabs.query({}, (tabs) => {
                tabs.forEach((tab) => {
                    const { id, url, title, status } = tab;
                    // 加入并刷新
                    if (!IsIllegalPages(url) && status === 'complete') {
                        console.log(`[Plugin] 添加页签记录 [${title}](${id})`);
                        globalThis.wnd2TabIds[id] = {
                            ...tab,
                            isOpt: false,
                        };
                        chrome.tabs.reload(id, {});
                    }
                    setIcon(id, url);
                });
            });
        } catch (e) {
            console.error('[Plugin]', e);
        }
    });

    chrome.windows.getAll((wins) => {
        const windows = wins.filter((win) => win.type === 'normal');

        const { id: winId } = windows[0];
        if (windows.length > 1) {
            console.error('[Plugin] 初始化时存在多个浏览器窗口，无法建立句柄映射关系。请关闭多余窗口后重试');
        } else {
            // 窗口唯一，直接加
            globalThis.nativeHost.request('query_hwnd', { windowId: winId });
            globalThis.wnd2WindowIds[winId] = {
                ...windows[0],
            };
        }
    });

    chrome.tabs.onRemoved.addListener((id) => {
        if (globalThis.wnd2TabIds[id]) {
            const { title } = globalThis.wnd2TabIds[id];
            delete globalThis.wnd2TabIds[id];
            console.log(`[Plugin] 移除页签记录 [${title || '未知标题'}](${id})`);
        }
    });

    chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
        const { id, url, title, status } = tab;

        const frames = chrome.webNavigation.getAllFrames({ tabId: id });

        if (!IsIllegalPages(tab.url) && status === 'complete') {
            // 合法页面计入wnd2TabIds
            if (!globalThis.wnd2TabIds[id]) {
                console.log(`[Plugin] 添加页签记录 [${title}](${id})`);
            } else {
                console.log(`[Plugin] 更新页签记录 [${title}](${id})`);
            }
            globalThis.wnd2TabIds[id] = {
                ...tab,
                isOpt: false,
                frames,
            };
        }

        setIcon(id, url);
    });

    // 设置图标
    chrome.tabs.onActivated.addListener((activeInfo) => {
        const { tabId } = activeInfo;
        chrome.tabs.get(tabId, ({ url }) => {
            setIcon(tabId, url);
        });
    });

    chrome.windows.onRemoved.addListener((winId) => {
        if (globalThis.wnd2WindowIds.hasOwnProperty(winId)) {
            delete globalThis.wnd2WindowIds[winId];
            console.log(`[Plugin] 移除窗口映射 (${winId})`);
        } else {
            console.warn(`[Plugin] 移除窗口映射失败：窗口被关闭，但未找到映射关系 (${winId})`);
        }
    });

    chrome.windows.onCreated.addListener((win) => {
        const { id } = win;
        globalThis.nativeHost.request('query_hwnd', { windowId: id });

        globalThis.wnd2WindowIds[id] = {
            ...win,
        };
    });

    chrome.cookies.onChanged.addListener(({ cookie, cause }) => {
        if (globalThis.rpaExtensionConfig?.listenCookieChange) {
            console.log(`[Cookies] ${cause}: `, cookie);
        }
    });
};

export { handleExtensionInstalled };
